package cn.turboinfo.fuyang.api.provider.common.repository.database.common.converter;

import cn.turboinfo.fuyang.api.domain.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.nio.charset.StandardCharsets;

@Converter
@Slf4j
public class DataEncryptConverter implements AttributeConverter<String, String> {

    private static final String ENCRYPT_KEY = "sGmnd1yRu5akPdvg";

    /**
     * 初始化向量(根据需求调整向量的值, 也可以将向量添加到入参变量中)
     */
    private static final byte[] SIV = new byte[16];

    // 数据加密
    @Override
    public String convertToDatabaseColumn(String attribute) {
        return SecurityUtils.encodeBase64(SecurityUtils.encryptAES(attribute.getBytes(), ENCRYPT_KEY.getBytes(), SIV));
    }

    // 数据解密
    @Override
    public String convertToEntityAttribute(String dbData) {
        if (!dbData.isBlank()) {
            try {
                return new String(SecurityUtils.decryptAES(SecurityUtils.decodeBase64(dbData), ENCRYPT_KEY.getBytes(), SIV), StandardCharsets.UTF_8);
            } catch (Exception e) {
                log.error("解密失败, 原始数据: {}, error: {}", dbData, e.getMessage());
                return dbData;
            }
        } else {
            return dbData;
        }
    }
}
